//
//  OASendApplyHtmlViewController.m
//  ERP
//
//  Created by goldeney on 15/3/24.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OASendApplyHtmlViewController.h"
#import "AESCrypt.h"
#import "TYMActivityIndicatorView.h"
#import "NSDictionary+DataFormat.h"

#import "ServiceConnect.h"
#import "UserLoginNSCoding.h"
#import "NSKeyedArchiverUserLogin.h"

#import "FileUploadModel.h"

@interface OASendApplyHtmlViewController ()<UIWebViewDelegate,TYMActivityIndicatorViewDelegate>

@property (nonatomic,strong) NSMutableArray *applyArray;
@property (nonatomic, strong) TYMActivityIndicatorView *activityIndicatorView;
@property (nonatomic, strong) NSMutableURLRequest *request;

@end

@implementation OASendApplyHtmlViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"填写申请表"];
        
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self
                                                                      action:@selector(uploadApplySelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    return self;
}

//获取上一个页面传递的参数
- (void)getPassingParameter:(id)object
{
    self.applyArray = object;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.delegate = self;
    
    //创建进度条
    if (!self.activityIndicatorView) {
        CGSize size = CGSizeMake(SuperWidth, SuperHeight- 64);
        CGFloat offsetX = size.width/2 - 107.0f/2;
        CGFloat offsetY = size.height/2 - 107.0f/2;
        
        self.activityIndicatorView = [[TYMActivityIndicatorView alloc] initWithActivityIndicatorStyle:TYMActivityIndicatorViewStyleLarge];
        _activityIndicatorView.hidesWhenStopped = YES;
        _activityIndicatorView.frame = CGRectMake(offsetX, offsetY, 107.0f, 107.0f);
        _activityIndicatorView.delegate = self;
        _activityIndicatorView.userInteractionEnabled = YES;
        [self.view addSubview:_activityIndicatorView];
    }
    
    self.webView.scalesPageToFit = YES;
    _webView.scrollView.bouncesZoom = NO;
    
    //添加数据
    NSMutableString *loadUrlString = [[NSMutableString alloc] initWithFormat:@"%@",self.applyArray[7],nil];
    [loadUrlString appendString:@"?"];
    [loadUrlString appendFormat:@"orgId=%@&",[AESCrypt encrypt:self.applyArray[0]]];
    [loadUrlString appendFormat:@"deptId=%@&",[AESCrypt encrypt:self.applyArray[1]]];
    [loadUrlString appendFormat:@"replaceSendApproval=%@&",[AESCrypt encrypt:self.applyArray[2]]];
    [loadUrlString appendFormat:@"templateId=%@&",[AESCrypt encrypt:self.applyArray[3]]];
    [loadUrlString appendFormat:@"processId=%@",[AESCrypt encrypt:self.applyArray[4]]];
    
    NSURL *url = [NSURL URLWithString:loadUrlString];
    self.request = [[NSMutableURLRequest alloc] initWithURL:url];
    [self.webView loadRequest:_request];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
        [storage deleteCookie:cookie];
    
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

#pragma mark -
#pragma mark TYMActivityIndicatorViewDelegate

- (void)refreshSelector:(id)button
{
    self.activityIndicatorView.hidden = NO;
    [self.activityIndicatorView startAnimating];
    [self.webView loadRequest:_request];
}

#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    _webView.userInteractionEnabled = NO;
    if (!self.activityIndicatorView.isAnimating) {
        self.activityIndicatorView.hidden = NO;
        [self.activityIndicatorView startAnimating];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    _webView.userInteractionEnabled = YES;
    if (self.activityIndicatorView.isAnimating) {
        self.activityIndicatorView.hidden = YES;
        [self.activityIndicatorView stopAnimating];
    }
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"===didFailLoadWithError===%@",error);
    _webView.userInteractionEnabled = NO;
    [self.activityIndicatorView showErrorView];
}

#pragma mark
#pragma mark - 申请提交验证

- (void)uploadApplySelector:(id)selector
{
    NSString *checkNodeData = [_webView stringByEvaluatingJavaScriptFromString:@"checkData();"];
    if (checkNodeData && ![checkNodeData isEqualToString:@""]) {
        [self setAlertViewMessage:checkNodeData];
        return;
    }
    
    NSString *getNodeData = [_webView stringByEvaluatingJavaScriptFromString:@"getFieldVals();"];
    if (!(getNodeData && ![getNodeData isEqualToString:@""] && ![getNodeData isEqualToString:@"[]"])) {
        [self setAlertViewMessage:@"请将申请单填写完整"];
        return;
    }
    
    //获取首个审批节点
    NSArray *applyFirstNodeArray = self.applyArray[5];
    NSDictionary *applyFirstNode = [applyFirstNodeArray firstObject];
    NSString *approvalNodeId = [applyFirstNode objectFormatStringForKey:@"id"];
    
    //处理节点信息
    NSString *jsonNodeString = nil;
    NSMutableArray *jsonNodeArray = [NSMutableArray array];
    for(NSDictionary *jsonDictionary in applyFirstNodeArray){
        NSMutableDictionary *mDictionary = [NSMutableDictionary dictionary];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"id"] forKey:@"id"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"tnodename"] forKey:@"tNodeName"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"tnodetype"] forKey:@"tNodeType"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"postid"] forKey:@"postId"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"rankId"] forKey:@"rankId"];
        [jsonNodeArray addObject:mDictionary];
    }
    if ([NSJSONSerialization isValidJSONObject:jsonNodeArray]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonNodeArray options:NSJSONWritingPrettyPrinted error:&error];
        jsonNodeString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    //处理附件信息
    NSString *jsonFileString = nil;
    NSArray *accessoryArray = self.applyArray[6];
    NSMutableArray *jsonFileArray = [NSMutableArray array];
    for(FileUploadModel *model in accessoryArray){
        NSDictionary *jsonDictionary = [model getFileInfo];
        NSMutableDictionary *mDictionary = [NSMutableDictionary dictionary];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"filePath"] forKey:@"FJPath"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"fileName"] forKey:@"FJName"];
        [jsonFileArray addObject:mDictionary];
    }
    if ([NSJSONSerialization isValidJSONObject:jsonFileArray]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonFileArray options:NSJSONWritingPrettyPrinted error:&error];
        jsonFileString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    //数据处理，打包上传
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:approvalNodeId forKey:@"approvalNodeId"];//首个审批节点
    [model setValue:self.applyArray[3] forKey:@"templateId"];//模板id
    [model setValue:self.applyArray[4] forKey:@"processId"];//流程id
    [model setValue:getNodeData forKey:@"FieldValues"];//流程节点
    [model setValue:jsonNodeString forKey:@"nodeList"];//申请表节点
    [model setValue:jsonFileString forKey:@"files"]; //附件
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_SendApproval" dataArray:model];
    [content showMBProgressHUD:self.navigationController labelText:@"正在提交"];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(result.resultArray && result.resultArray.count>0){
            //result：返回结果(1成功，0失败)
            NSDictionary *resultArray = [result.resultArray firstObject];
            NSInteger result = [[resultArray objectFormatForKey:@"result"] integerValue];
            if (result == 0) [self setAlertViewMessage:@"提交失败，请重新尝试"];
            else [self successUpLoadBriefcase];
            
        } else {
            [self setAlertViewMessage:@"提交申请失败，请重新尝试提交"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==failed===%@",error);
        [self setAlertViewMessage:@"提交申请失败，请重新尝试提交"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===abnormal==%@",error);
        [self setAlertViewMessage:@"网络异常，请检查网络是否连接正常"];
    }];
}

#pragma mark
#pragma mark - UIAlertView

- (void)setAlertViewMessage:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

- (void)successUpLoadBriefcase
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"提交申请成功，请耐心等待审批" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}


#pragma mark
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
